import React, { useState, useEffect, useRef } from 'react';
import { AppScreen } from '../types';

interface GuideStep {
  targetId: string;
  title: string;
  content: string;
  screen: AppScreen;
  position?: 'top' | 'bottom' | 'left' | 'right';
  isInteraction?: boolean; // If true, user must click the element to advance
}

const STEPS: GuideStep[] = [
  {
    targetId: 'settings-btn',
    title: '第1步: 设置',
    content: '欢迎！一切从这里开始。点击【设置】，配置您的AI服务，这是让魔法发生的第一步。',
    screen: AppScreen.MainMenu,
    position: 'top',
    isInteraction: true,
  },
  {
    targetId: 'api-channels-section',
    title: '第2步: 配置API',
    content: '在这里添加您的API渠道和模型。这是与AI沟通的桥梁。完成后请保存并点击“返回主菜单”。',
    screen: AppScreen.Settings,
    position: 'bottom',
    isInteraction: true, 
  },
  {
    targetId: 'create-game-btn',
    title: '第3步: 创建游戏',
    content: '太棒了！配置好API后，点击这里，开始构建您的第一个游戏世界。',
    screen: AppScreen.MainMenu,
    position: 'top',
    isInteraction: true,
  },
   {
    targetId: 'create-and-enter-btn',
    title: '第4步: 填写设定',
    content: '请填写您的游戏名称、背景和规则，然后点击“创建并进入游戏”。',
    screen: AppScreen.CreateGame,
    position: 'bottom',
    isInteraction: true,
  },
  {
    targetId: 'ai-config-btn',
    title: '第5步: 生成AI剧本',
    content: '您的世界已就绪！现在，点击这里，为AI生成一套“剧本”（提示词）。',
    screen: AppScreen.GameScreen,
    position: 'bottom',
    isInteraction: true,
  },
  {
    targetId: 'generate-prompts-btn',
    title: '第6步: 一键生成',
    content: '点击这个按钮，AI就会根据您的设定自动生成一套提示词。',
    screen: AppScreen.GameScreen, 
    position: 'bottom',
    isInteraction: true,
  },
  {
      targetId: 'save-ai-config-btn',
      title: '第7步: 保存配置',
      content: '太棒了！现在点击“保存配置”，游戏就会自动开始。',
      screen: AppScreen.GameScreen,
      position: 'top',
      isInteraction: true,
  },
  {
    targetId: 'player-action-area',
    title: '第8步: 开始冒险！',
    content: '冒险开始了！您可以点击AI提供的选项，或是在输入框中发挥想象力，自由行动。',
    screen: AppScreen.GameScreen,
    position: 'top',
    isInteraction: false, // Informational
  },
  {
    targetId: 'rulebook-btn',
    title: '工具栏介绍 (1/7)',
    content: '【规则书】您可以随时点击这里，编辑游戏的核心背景和规则。',
    screen: AppScreen.GameScreen,
    position: 'bottom',
    isInteraction: false,
  },
  {
    targetId: 'ai-config-btn',
    title: '工具栏介绍 (2/7)',
    content: '【AI配置】我们用过这个了。您可以随时返回这里，微调AI的行为，甚至与AI讨论来优化提示词。',
    screen: AppScreen.GameScreen,
    position: 'bottom',
    isInteraction: false,
  },
  {
    targetId: 'ai-context-btn',
    title: '工具栏介绍 (3/7)',
    content: '【AI上下文】(高级功能) 点击这里可以查看为了生成当前回合而发送给AI的完整提示词。',
    screen: AppScreen.GameScreen,
    position: 'bottom',
    isInteraction: false,
  },
  {
    targetId: 'backtrack-btn',
    title: '工具栏介绍 (4/7)',
    content: '【回溯】后悔了？点击这里可以撤销上一步操作，回到之前的选择点。',
    screen: AppScreen.GameScreen,
    position: 'bottom',
    isInteraction: false,
  },
  {
    targetId: 'save-game-btn',
    title: '工具栏介绍 (5/7)',
    content: '【保存】游戏每回合都会自动保存，但您也可以随时点击这里手动保存。',
    screen: AppScreen.GameScreen,
    position: 'bottom',
    isInteraction: false,
  },
  {
    targetId: 'export-game-btn',
    title: '工具栏介绍 (6/7)',
    content: '【导出】使用这里的功能，可以将您的游戏存档或故事导出为文件，与朋友分享。',
    screen: AppScreen.GameScreen,
    position: 'bottom',
    isInteraction: false,
  },
  {
    targetId: 'main-menu-btn',
    title: '工具栏介绍 (7/7)',
    content: '【主菜单】点击这里可以返回主菜单。',
    screen: AppScreen.GameScreen,
    position: 'left',
    isInteraction: false,
  },
  {
    targetId: 'side-panels-info',
    title: '最后一步: 游戏面板',
    content: '随时留意左右两侧面板的变化，它们记录着您的角色状态和故事的关键进展。祝您旅途愉快！',
    screen: AppScreen.GameScreen,
    position: 'top',
    isInteraction: false,
  }
];


interface InteractiveGuideProps {
  isActive: boolean;
  currentStep: number;
  onNext: () => void;
  onEnd: () => void;
  currentScreen: AppScreen;
}

const InteractiveGuide: React.FC<InteractiveGuideProps> = ({ isActive, currentStep, onNext, onEnd, currentScreen }) => {
  // FIX: Use a boolean state for visibility to avoid issues with CSSProperties type definitions.
  const [highlightStyle, setHighlightStyle] = useState<React.CSSProperties>({});
  const [popoverStyle, setPopoverStyle] = useState<React.CSSProperties>({});
  const [isGuideVisible, setIsGuideVisible] = useState(false);
  const [popoverPosition, setPopoverPosition] = useState<'top' | 'bottom' | 'left' | 'right'>('bottom');
  const searchIntervalRef = useRef<number | null>(null);

  const step = STEPS[currentStep];

  const stopSearching = () => {
    if (searchIntervalRef.current) {
      clearInterval(searchIntervalRef.current);
      searchIntervalRef.current = null;
    }
  };

  useEffect(() => {
    stopSearching();

    if (!isActive || !step || step.screen !== currentScreen) {
      setIsGuideVisible(false);
      return;
    }

    let attempts = 0;
    const maxAttempts = 40; // 4 seconds
    const intervalTime = 100;

    const findAndPosition = () => {
      attempts++;
      if (attempts > maxAttempts) {
        console.warn(`InteractiveGuide: Could not find target element [data-guide-id="${step.targetId}"] after ${maxAttempts * intervalTime / 1000} seconds.`);
        stopSearching();
        return;
      }
      
      const targetElement = document.querySelector<HTMLElement>(`[data-guide-id="${step.targetId}"]`);
      
      if (targetElement && targetElement.offsetParent !== null) {
        const targetRect = targetElement.getBoundingClientRect();
        if (targetRect.width === 0 && targetRect.height === 0) return;
        
        stopSearching();

        const margin = 15;

        setHighlightStyle({
            position: 'fixed',
            width: `${targetRect.width + 12}px`,
            height: `${targetRect.height + 12}px`,
            top: `${targetRect.top - 6}px`,
            left: `${targetRect.left - 6}px`,
        });
        
        const estimatedPopoverHeight = 150; 
        const estimatedPopoverWidth = 288; // w-72

        let pos = step.position || 'bottom';
        const space = {
            top: targetRect.top, bottom: window.innerHeight - targetRect.bottom,
            left: targetRect.left, right: window.innerWidth - targetRect.right,
        };
        
        if (pos === 'bottom' && space.bottom < estimatedPopoverHeight + margin && space.top > space.bottom) pos = 'top';
        else if (pos === 'top' && space.top < estimatedPopoverHeight + margin && space.bottom > space.top) pos = 'bottom';
        else if (pos === 'right' && space.right < estimatedPopoverWidth + margin && space.left > space.right) pos = 'left';
        else if (pos === 'left' && space.left < estimatedPopoverWidth + margin && space.right > space.left) pos = 'right';
        
        setPopoverPosition(pos);

        let top = 0, left = 0;
        let transform = '';
        switch (pos) {
            case 'top':
                top = targetRect.top - margin;
                left = targetRect.left + targetRect.width / 2;
                transform = 'translate(-50%, -100%)';
                break;
            case 'left':
                top = targetRect.top + targetRect.height / 2;
                left = targetRect.left - margin;
                transform = 'translate(-100%, -50%)';
                break;
            case 'right':
                top = targetRect.top + targetRect.height / 2;
                left = targetRect.right + margin;
                transform = 'translateY(-50%)';
                break;
            default: // bottom
                top = targetRect.bottom + margin;
                left = targetRect.left + targetRect.width / 2;
                transform = 'translateX(-50%)';
                break;
        }

        setPopoverStyle({
            position: 'fixed',
            top: `${top}px`,
            left: `${left}px`,
            transform: transform,
        });
        setIsGuideVisible(true);
      }
    };

    searchIntervalRef.current = window.setInterval(findAndPosition, intervalTime);

    return () => stopSearching();
  }, [isActive, currentStep, currentScreen, step]);

  useEffect(() => {
      const handleResize = () => {
          setIsGuideVisible(false);
      };
      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
  }, []);

  if (!isActive || !step || step.screen !== currentScreen || !isGuideVisible) {
    return null;
  }
  
  const showNextButton = !step.isInteraction;

  return (
    <div className="fixed inset-0 z-[999] pointer-events-none">
      <div
        className={`absolute w-72 bg-gray-800 p-4 rounded-lg shadow-xl border border-gray-700 z-[1000] transition-opacity duration-300 pointer-events-auto guide-popover pos-${popoverPosition}`}
        style={popoverStyle}
      >
        <h3 className="text-lg font-bold text-cyan-400">{step.title}</h3>
        <p className="mt-2 text-sm text-gray-300">{step.content}</p>
        <div className="mt-4 flex justify-between items-center">
          <button onClick={onEnd} className="text-xs text-gray-400 hover:text-white">跳过</button>
          <div className="flex items-center gap-3">
            <span className="text-xs text-gray-500">{currentStep + 1} / {STEPS.length}</span>
            {showNextButton && (
                <button
                onClick={currentStep === STEPS.length - 1 ? onEnd : onNext}
                className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm"
                >
                {currentStep === STEPS.length - 1 ? '完成' : '下一步'}
                </button>
            )}
          </div>
        </div>
      </div>

      <div
        className="guide-highlight-pulse bg-transparent rounded-lg shadow-[0_0_0_9999px_rgba(0,0,0,0.7)] transition-all duration-300"
        style={highlightStyle}
      ></div>
    </div>
  );
};

export default InteractiveGuide;